package server.network;
/**
 * 验证线程,发上线包,刷新上线信息
 */
import java.io.*;
import java.net.Socket;
import java.util.*;

import server.config.Public;
import server.doc.xml.XMLUserProfile;
import server.models.*;
import server.views.ServerMain;

import common.message.Message;
import common.message.clientSend.*;
import common.message.serverSend.*;
import common.types.*;

public class ValidateThread implements Runnable {

	private Socket socket;

	private Message clientPacket;
	private boolean success;
	private XMLUserProfile xmlProfile = XMLUserProfile.getInstance();
	private ServerMain f;
	public ValidateThread(Socket s, ServerMain f) {
		super();
		socket = s;
		this.f = f;
	}

	public void run() {
		ObjectInputStream ois = null;
		ObjectOutputStream oos = null;
		try {
			ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
			oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
			clientPacket = (Message) ois.readObject();
			success = false;
			// 判断包的类型
			if (clientPacket instanceof UserLoginMsg) {
				// 验证登录包是否正确
				UserLoginMsg loginPacket = (UserLoginMsg) clientPacket;
				int uid = loginPacket.getUserID();//登录的用户id 
				String pwd = loginPacket.getPassword();
				try {
					UserProfile profile = xmlProfile.getUser(uid);
					// user already online?
					if (Public.status.getStatus(uid) == StatusType.offline) {
						// 不在线
						// 返回数据库中用户密码
						if (pwd.equals(profile.getPassword())) {
							// 验证通过
							// 修改用户信息,把是否在线字段修改成1
							oos.writeObject(new ServerConfirmMsg(uid, loginPacket));
							
							oos.writeObject(new UserProfileMsg(uid, uid, profile.getName(),
									profile.getGender(), profile.getAge()));

							// 取该用户的好友和好友群信息，发送到客户端
							ArrayList<Integer> friends = profile.getFriends();
							HashMap<Integer, String> friendsName = new HashMap<Integer, String>();
							HashMap<Integer, StatusType> friendsStatus = new HashMap<Integer, StatusType>();
							for (Integer fuid : friends) {
								friendsName.put(fuid, xmlProfile.getUser(fuid).getName());
								friendsStatus.put(fuid, Public.status.getStatus(fuid));
							}
							oos.writeObject(new FriendListMsg(uid, friends, friendsName, friendsStatus));

							success = true;
						} else {
							// 发密码不正确的验证包
							oos.writeObject(new ServerDenyMsg(uid, "username and password not match", loginPacket));
						}
					} else {
						// 发号码已登录的验证包
						oos.writeObject(new ServerDenyMsg(uid, "userID already logged in", loginPacket));
					}
				} catch (Error e) {
					// 发号码不存在的验证包
					oos.writeObject(new ServerDenyMsg(uid, "userID doesn't exist", loginPacket));
				}
				oos.flush();

				// 判断是否登录成功
				if (success == true) {
//					TopPanel.setTShow(uid,4);
					// 创建线程,接收客户端信息
					ReceiveThread receiveThread = new ReceiveThread(uid, ois, f);
					Thread myReceiveThread = new Thread(receiveThread);
					myReceiveThread.start();
					// 保存信息到全局变量
					Public.clientThreads.put(new Integer(uid), myReceiveThread);
					Public.clientSocket.put(new Integer(uid), socket);
					Public.clientOStream.put(new Integer(uid), oos);
					Public.clientIStream.put(new Integer(uid), ois);

					// 向所有用户发上线包
					for (Integer user : Public.status.getOnlineUsers()) {
						ObjectOutputStream tempOOS = Public.clientOStream.get(user);
						tempOOS.writeObject(new UserStatusMsg(user, uid, StatusType.online));
						tempOOS.flush();
					}

					Public.status.setStatus(uid, StatusType.online);

					//更新显示在服务器端的上线用户信息
					ArrayList<ArrayList<String>> profileList = new ArrayList<ArrayList<String>>();
					for (Integer user : Public.status.getOnlineUsers()) {
						ArrayList<String> strProfile = new ArrayList<String>();
						strProfile.add(user.toString());
						UserProfile profile = xmlProfile.getUser(user.intValue());
						strProfile.add(profile.getName());
						strProfile.add(profile.getGender().toString());
						strProfile.add(Public.dateFormat.format(Public.status.getOnlineTime(user.intValue())));
						profileList.add(strProfile);
					}
					f.getServerMngPanel().getTablePanel().getDataModel().setData(profileList);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} 
	}


}
